package com.liu.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.commonutils.ReturnResult;
import com.liu.eduservice.entity.EduTeacher;
import com.liu.eduservice.entity.vo.TeacherQuery;
import com.liu.eduservice.service.EduTeacherService;
import com.liu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 * @since 2022-05-03
 */
@RestController
@Api(description = "讲师管理")
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class EduTeacherController {


    @Autowired
    private EduTeacherService eduTeacherService;


    // 查询讲师表所有数据
    @ApiOperation(value = "查询所有讲师列表")
    @GetMapping("/findAll")
    public ReturnResult list() {
        List<EduTeacher> list = eduTeacherService.list(null);
        return ReturnResult.ok().data("items", list);
    }

    // 逻辑删除讲师
    @ApiOperation(value = "根据ID删除讲师")
    @DeleteMapping("/deleteTeacherById/{id}")
    public ReturnResult deleteTeacherById(@ApiParam(name = "id",
                                                    value = "讲师ID",
                                                    required = true)
                                          @PathVariable String id) {
        boolean flag = eduTeacherService.removeById(id);
        if (flag) {
            return ReturnResult.ok();
        } else {
            return ReturnResult.error();
        }
    }

    // 分页查询
    @GetMapping("/pageList/{page}/{limit}")
    @ApiOperation(value = "分页查询")
    public ReturnResult pageSelect(@ApiParam(name = "page", value = "首页", required = true)
                                   @PathVariable Long page,
                                   @ApiParam(name = "limit", value = "每页记录数", required = true)
                                   @PathVariable Long limit) {
        // 第一步创建对象
        Page<EduTeacher> pageParam = new Page<>(page, limit);

        // 将对象封装到创建的对象中
        eduTeacherService.page(pageParam, null);

        // 获取查询到的对象
        List<EduTeacher> selectObj = pageParam.getRecords();

        // 获取查询到的总记录数
        long totalNumber = pageParam.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("totalNumber", totalNumber);
        map.put("selectObj", selectObj);
        return ReturnResult.ok().data(map);
    }

    // 多条件查询讲师带分页
    @ApiOperation(value = "多条件查询讲师带分页")
    @PostMapping("/pageTeacherCondition/{page}/{limit}")
    public ReturnResult pageTeacherCondition(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
                                             @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit,
                                             @RequestBody(required = false) TeacherQuery teacherQuery) {//通过封装TeacherQuery对象来直接传递查询条件
        //创建分页page对象
        Page<EduTeacher> pageParam = new Page<>(page, limit);

        //调用方法实现多条件分页查询
        QueryWrapper<EduTeacher> queryWrapper = new QueryWrapper<>();
        // 需要查询的条件
        String teacherName = teacherQuery.getName();
        Integer teacherLevel = teacherQuery.getLevel();
        String beginTime = teacherQuery.getBegin();
        String endTime = teacherQuery.getEnd();

        // 判断条件(将条件串联起来)
        //判断条件值是否为空，如果不为空，拼接条件
        //判断是否有传入教师名
        if (!StringUtils.isEmpty(teacherName)) {
            //构建条件
            queryWrapper.like("name", teacherName);//参数1：数据库字段名； 参数2：模糊查询的值
        }
        //判断是否传入教师头衔
        if (!StringUtils.isEmpty(teacherLevel)) {
            //构造条件
            queryWrapper.eq("level", teacherLevel);
        }
        if (!StringUtils.isEmpty(beginTime)) {
            //构造条件
            queryWrapper.ge("gmt_create", beginTime);//ge：大于等于
        }
        if (!StringUtils.isEmpty(beginTime)) {
            //构造条件
            queryWrapper.le("gmt_modified", endTime);//le:小于等于
        }

        // 根据创建时间降序排序(创建一个就放在表的开头)
        queryWrapper.orderByDesc("gmt_create");

        // 调用方法，实现按条件查询并且分页
        eduTeacherService.page(pageParam, queryWrapper);

        //获取查询到的数据
        List<EduTeacher> records = pageParam.getRecords();

        //获取总记录数(在表中查询到满足条件的总数是多少)
        long total = pageParam.getTotal();
        return ReturnResult.ok().data("total", total).data("rows", records);

    }


    // 添加一个对象在表中
    @ApiOperation(value = "添加对象")
    @PostMapping("/addObj")
    public ReturnResult addObj(@RequestBody(required = false) EduTeacher eduTeacher) {

        boolean save = eduTeacherService.save(eduTeacher);
        if (save) {
            return ReturnResult.ok();
        } else {
            return ReturnResult.error();
        }
    }


    // 根据id查询,用于信息回显
    @ApiModelProperty(value = "根据id查询")
    @ApiOperation(value = "根据id查询查询对象")
    @GetMapping("/getById/{id}")
    public ReturnResult getById(@PathVariable String id) {
        EduTeacher teacher = eduTeacherService.getById(id);
        return ReturnResult.ok().data("item", teacher);
    }


    // 修改讲师
    @ApiModelProperty(value = "修改讲师")
    @ApiOperation(value = "修改讲师对象")
    @PostMapping("/updateById")
    public ReturnResult updateById(@RequestBody EduTeacher teacher) {
        boolean flag = eduTeacherService.updateById(teacher);
        if (flag) {
            return ReturnResult.ok();
        } else {
            return ReturnResult.error();
        }
    }

    // 执行自定义异常处理的实例
    @ApiOperation(value = "异常信息捕获")
    @GetMapping("/error")
    public ReturnResult method() {
        // 会出现异常代码块需要捕获
        try {
            int errorMsg = 10 / 0;
        } catch (Exception exception) {
            throw new GuliException(20001, "执行自定义异常处理类");
        }

        return ReturnResult.error().data("异常处理信息是：", new GuliException(20001, "执行自定义异常处理类"));
    }

}

